﻿using Tool.Models;
using Volo.Abp.DependencyInjection;

namespace Tool.Services
{
    public class EncryptHelper : IScopedDependency
    {
        private IHttpClientFactory _httpClientFactory;

        public EncryptHelper(IHttpClientFactory httpClientFactory)
        {
            _httpClientFactory = httpClientFactory;
        }

        public async Task<string?> DecryptAsync(string source)
        {
            if (string.IsNullOrEmpty(source))
            {
                return string.Empty;
            }
            try
            {
                using var encryptClient = _httpClientFactory.CreateClient("encrypt");
                var res = await encryptClient.PostAsJsonAsync("/gwhome-base-cache2/decrypt_cache", new { data = source });
                if (res.IsSuccessStatusCode)
                {
                    return (await res.Content.ReadFromJsonAsync<ApiResponseDto<string>>())?.Data;
                }
                return source;
            }
            catch (Exception ex)
            {
                throw new Exception($"An error occurred while decrypting: {ex.Message}", ex);
            }
        }

        public async Task<string?> EncryptAsync(string source)
        {
            if (string.IsNullOrEmpty(source))
            {
                return string.Empty;
            }
            try
            {
                using var encryptClient = _httpClientFactory.CreateClient("encrypt");
                var res = await encryptClient.PostAsJsonAsync("/gwhome-base-cache2/encrypt_cache", new { data = source });
                if (res.IsSuccessStatusCode)
                {
                    return (await res.Content.ReadFromJsonAsync<ApiResponseDto<string>>())?.Data;
                }
                return source;
            }
            catch (Exception ex)
            {
                throw new Exception($"An error occurred while encrypting: {ex.Message}", ex);
            }
        }
    }
}
